package cn.cloudtogo.server.atomapi;

import cn.cloudtogo.common.atomapi.token.ApiToken;
import cn.cloudtogo.common.model.ApiTokenDao;
import cn.cloudtogo.common.model.ApiTokenModel;
import cn.cloudtogo.common.model.ExternalDatasourceDao;
import cn.cloudtogo.common.model.ExternalDatasourceModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author yaolianhua789@gmail.com
 **/
@Component
@Slf4j
public class ExternalDatasourceGlobalApiTokenMigrator {

    private final GendbApiTokenService apiTokenService;
    private final ExternalDatasourceDao externalDatasourceDao;
    private final ApiTokenDao apiTokenDao;

    public ExternalDatasourceGlobalApiTokenMigrator(GendbApiTokenService apiTokenService,
                                                    ExternalDatasourceDao externalDatasourceDao,
                                                    ApiTokenDao apiTokenDao) {
        this.apiTokenService = apiTokenService;
        this.externalDatasourceDao = externalDatasourceDao;
        this.apiTokenDao = apiTokenDao;
    }

    public synchronized void migrate() {

        List<String> uuidList = externalDatasourceDao.list()
                .stream()
                .map(ExternalDatasourceModel::getUuid)
                .collect(Collectors.toList());

        AtomicInteger count = new AtomicInteger(0);
        StopWatch watch = new StopWatch();
        watch.start();
        for (String uuid : uuidList) {
            ApiTokenModel apiTokenModel = apiTokenDao.query(uuid, "Global");
            if (null != apiTokenModel) {
                continue;
            }
            try {
                ApiTokenCreateParam ofGlobal = ApiTokenCreateParam.ofGlobal(uuid, "Global");
                ApiToken apiToken = apiTokenService.generate(ofGlobal);
                count.incrementAndGet();
                log.info("Migrate [{}] Api token generated for datasource [{}]", apiToken.getNotes(), uuid);
            } catch (Exception e) {
                //
            }

        }

        watch.stop();
        double seconds = watch.getTotalTimeSeconds();
        log.info("Migrate Global api-token successful. total size '{}', Takes '{}s'", count.get(), seconds);
    }
}
